package com.zplh.zplh_android_yk.ui;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.zplh.zplh_android_yk.BuildConfig;
import com.zplh.zplh_android_yk.R;
import com.zplh.zplh_android_yk.UserManager;
import com.zplh.zplh_android_yk.bean.BindingBean;
import com.zplh.zplh_android_yk.bean.CheckImeiBean;
import com.zplh.zplh_android_yk.intf.BindingServices;
import com.zplh.zplh_android_yk.intf.CheckBinding;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import zplh.com.commonlibrary.networker.NetCustomSubscriber;
import zplh.com.commonlibrary.networker.NetWorker;
import zplh.com.commonlibrary.utils.DialogUtils;
import zplh.com.commonlibrary.utils.ShellUtils;
import zplh.com.commonlibrary.utils.SpUtils;
import zplh.com.commonlibrary.utils.StringUtils;
import zplh.com.commonlibrary.utils.SystemParamerUtils;
import zplh.com.commonlibrary.utils.ToastUtils;
import zplh.com.resourcelibrary.constants.SpConstants;

/**
 * Created by yong hao zeng on 2018/6/29.
 */
public class BindingActivity extends BaseActivity {
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.et_imei)
    EditText etImei;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.bt_binding)
    Button btBinding;
    @BindView(R.id.bt_get_imei)
    Button btGetImei;
    @BindView(R.id.bt_versions)
    Button btVersions;
    @BindView(R.id.bt_change_binding)
    Button btChangeBinding;
    private ProgressDialog initDialog;
    String imei = "";
    boolean isImei = true;
    @Override
    int getLayoutId() {
        return R.layout.activity_binding;
    }

    @Override
    void onFirstStart() {
        initData();
    }

    private void initData() {

        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
            tvVersion.setText(packageInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (initDialog == null)
            initDialog = DialogUtils.creatCircleDialog(this, "初始化中");
        if (!initDialog.isShowing())
            initDialog.show();

        String mid = SpUtils.getValue(SpConstants.SYSTEM_PARAMETER_SP, SpConstants.MID);
        if (TextUtils.isEmpty(mid)) {
            initIMEI();
        }else {
            UserManager.init(mid);
            MainActivity.starter(BindingActivity.this);
            initDialog.dismiss();
        }

        initApp();

    }


    @OnClick(R.id.bt_change_binding)
    public void onClick(View view){
        if (isImei)
        imei = SystemParamerUtils.getImsi(this);
        else {
            imei = SystemParamerUtils.getIMEIBySystem(this);
        }
        checkBinding();

        isImei = !isImei;
    }


    @SuppressLint("CheckResult")
    private void initApp() {
//        Observable.create(emitter -> {
//            initPermission();
//            emitter.onNext(0);
//        }).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(o -> {
//                            LogUtils.d("INIT","权限初始化完毕" );
//                    ToastUtils.showToastSuccess(MyApplication.getCurrentActivity(), "权限初始化完毕");
//                }
//                );

    }



    private void initPermission(){

        ShellUtils.execCommand("pm grant com.zplh.zplh_android_yk android.permission.WRITE_EXTERNAL_STORAGE",true);
        ShellUtils.execCommand("pm grant com.zplh.zplh_android_yk android.permission.ACCESS_COARSE_LOCATION",true);
        ShellUtils.execCommand("pm grant com.zplh.zplh_android_yk android.permission.READ_CONTACTS",true);
        ShellUtils.execCommand("pm grant com.zplh.zplh_android_yk android.permission.READ_PHONE_STATE",true);
        ShellUtils.execCommand("pm grant com.tencent.mm android.permission.READ_PHONE_STATE",true);
        ShellUtils.execCommand("pm grant com.tencent.mm android.permission.WRITE_SETTINGS",true);
        ShellUtils.execCommand("pm grant com.tencent.mm android.permission.READ_CONTACTS",true);
        ShellUtils.execCommand("pm grant com.tencent.mm android.permission.CAMERA",true);
        ShellUtils.execCommand("pm grant com.tencent.mm android.permission.RECORD_AUDIO",true);
    }

    @SuppressLint("CheckResult")
   private void initIMEI() {
        Observable.create((ObservableOnSubscribe<String>) emitter -> emitter.onNext(SystemParamerUtils.getImei()))
                .onErrorReturn(throwable -> "请随意输入一个imei号")
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())

                .subscribe(s -> {

                    imei = s;
                    UserManager.getInstance().setImei(s);
                    etImei.setText(s);
                    checkBinding();
                });
    }


    private void checkBinding() {
        if (TextUtils.isEmpty(etImei.getText().toString().trim())){
            initDialog.dismiss();
           Toast.makeText(this,"请填写imei" , Toast.LENGTH_LONG).show();
            return;
        }

        HashMap<String,String> queryMap = new HashMap();
        queryMap.put("imei",imei);
        queryMap.put("status", "1");
        queryMap.put("batch", BuildConfig.VERSION_NAME);


       CheckBinding checkBinding = NetWorker.getInstance().getRetrofit().create(CheckBinding.class);
        Observable<CheckImeiBean> rxData = checkBinding.getRxData(queryMap);


        NetWorker.getInstance().createNetAsync(rxData, new NetCustomSubscriber<CheckImeiBean>() {
                    @Override
                    public void onNext(CheckImeiBean o) {
                        initDialog.dismiss();
                        String data = o.getData();

                        if (TextUtils.isEmpty(data)){
                            //未绑定
                            Toast.makeText(BindingActivity.this,"请绑定",Toast.LENGTH_LONG).show();

                        }else {
                            SpUtils.putValue(SpConstants.SYSTEM_PARAMETER_SP,SpConstants.MID,data);
                            UserManager.init(data);
                            MainActivity.starter(BindingActivity.this);

                        }
                    }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                    initDialog.dismiss();
                ToastUtils.showToastError(BindingActivity.this,e.getLocalizedMessage());
                    }
        });
    }




    @OnClick({R.id.bt_binding, R.id.bt_get_imei, R.id.bt_versions})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_binding:

                if (TextUtils.isEmpty(etImei.getText().toString())){
                    Toast.makeText(BindingActivity.this, "填写imei",Toast.LENGTH_LONG).show();
                    return;
                }
               String code =  etCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)){
                    Toast.makeText(BindingActivity.this,"填写激活码",Toast.LENGTH_LONG ).show();
                    return;
                }
                imei = etImei.getText().toString();
                binding(imei,code);
                break;
            case R.id.bt_get_imei:
                Observable.create((ObservableOnSubscribe<String>) emitter -> emitter.onNext(SystemParamerUtils.getImei()))
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(s -> {
                            this.imei = s;
                            etImei.setText(s);
                            UserManager.getInstance().setImei(this.imei);
                        });
                break;
            case R.id.bt_versions:
                  Intent intent = new Intent();
                  intent.setClass(this,VersionActivity.class);
                  startActivity(intent);
        }
    }

    private void binding(String imei, String code) {
        ProgressDialog dialog = DialogUtils.creatCircleDialog(this, "绑定中");
        dialog.show();
        if (TextUtils.isEmpty(StringUtils.findByReg("[1-9]\\d*|0", code)))
        {

            Toast.makeText(this,"注册码可能不符合规格",Toast.LENGTH_LONG ).show();
        }
        HashMap<String,String> query = new HashMap<>();
        query.put("id",StringUtils.findByReg("[1-9]\\d*|0",code));
        query.put("code",code);
        query.put("imei",imei);
        Observable<BindingBean> rxData = NetWorker.getInstance()
                .getRetrofit()
                .create(BindingServices.class)
                .getRxData(query);
        NetWorker.getInstance().createNetAsync(rxData, new NetCustomSubscriber<BindingBean>() {
            @Override
            public void onNext(BindingBean o) {
                dialog.dismiss();
                if (o.getRet().equals("200")){
                    UserManager.getInstance().setId(o.getData().getUid());
                    SpUtils.putValue(SpConstants.SYSTEM_PARAMETER_SP,SpConstants.MID,o.getData().getUid());
                    MainActivity.starter(BindingActivity.this);
                }else {
                    ToastUtils.showToastError(BindingActivity.this,"已绑定");
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtils.showToastError(BindingActivity.this,e.getLocalizedMessage());
                dialog.dismiss();
            }
        });

    }
}
